import { NextRequest, NextResponse } from 'next/server'
import { createServerClient } from '@supabase/ssr'
import { updateUser } from '@/lib/database'

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    // 从URL中提取用户ID，因为params可能由于某些原因不可用
    const url = new URL(request.url)
    const id = url.pathname.split('/').slice(-2)[0]

    if (!id) {
      return NextResponse.json({
        success: false,
        error: '缺少用户ID参数'
      }, { status: 400 })
    }

    const body = await request.json()
    const { role } = body

    if (!role) {
      return NextResponse.json({
        success: false,
        error: '角色信息不能为空'
      }, { status: 400 })
    }

    // 更新用户角色
    const updatedUser = await updateUser(id, { role })

    return NextResponse.json({
      success: true,
      data: updatedUser,
      message: '用户角色更新成功'
    })
  } catch (error) {
    console.error('更新用户角色失败:', error)
    return NextResponse.json({
      success: false,
      error: '更新用户角色失败'
    }, { status: 500 })
  }
}